//
//  XLHomeTableViewController.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/8/29.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit
import YYModel

class XLHomeTableViewController: XLVisitorTableViewController {
    
    lazy var  homeViewModel: XLHomeViewModel = {
        let homeViewModel = XLHomeViewModel()
        return homeViewModel
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if userLogin == false{
            visitorView.setVisitorView(imageName: nil, message: "首页")
            return
        }
        
        setupUI()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    
    
    
    func setupUI() {
        
        let leftBtn = UIButton()
        leftBtn.setImage(#imageLiteral(resourceName: "navigationbar_friendsearch"), for: .normal)
        leftBtn.setImage(#imageLiteral(resourceName: "navigationbar_friendsearch_highlighted"), for: .highlighted)
        leftBtn.sizeToFit()
        
        let rightBtn = UIButton()
        rightBtn.setImage(#imageLiteral(resourceName: "navigationbar_pop"), for: .normal)
        rightBtn.setImage(#imageLiteral(resourceName: "navigationbar_pop_highlighted"), for: .highlighted)
        rightBtn.sizeToFit()
        
        //navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        //navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", target: self, action: #selector (nothing))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: #selector(push))
        
        tableView.register(XLStatusCell.classForCoder(), forCellReuseIdentifier: "cellid")
        //自适应行高
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 150
        
        // 关闭分割线
        tableView.separatorStyle = .none
        // 设置tableView的footerView
        tableView.tableFooterView = pullUpView
        
        //tableView本身的刷新数据属性
        //self.refreshControl = UIRefreshControl()
        //self.refreshControl?.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
        
        tableView.addSubview(xlrefreshControl)
        xlrefreshControl.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
        
        // 添加下拉刷新提示的label
        self.navigationController!.view.insertSubview(pullDownTipLabel, belowSubview: self.navigationController!.navigationBar)
        // 设置刷新控件的y值
        pullDownTipLabel.frame.origin.y = self.navigationController!.navigationBar.frame.maxY - pullDownTipLabel.frame.size.height

        
        loadData()
    }
    
    func push() {
        let vc = XLTempController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func nothing() {
        
    }
    
    //加载数据
    internal func loadData() {
            homeViewModel.loadData(isPullUp: pullUpView.isAnimating) { (isSuccess, count) in
            if isSuccess {
                //数据请求成功, 就刷新数据
                self.tableView.reloadData()
            }else{
                print("数据加载错误")
            }
                // 如果不是上拉加载，才去显示这个label
                if !self.pullUpView.isAnimating {
                    // 显示下拉刷新的label
                    self.showTipLabel(count: count)
                }
                print("加载回来\(count)条")

            // 结束刷新
            self.pullUpView.stopAnimating()
            self.xlrefreshControl.endRefreshing()
        }
    }
    
    /// 下拉刷新的时候显示提示label
    ///
    /// - parameter count: <#count description#>
    private func showTipLabel(count: Int) {
        
        if pullDownTipLabel.isHidden == false {
            // 如果当前已经再显示，那么就直接返回
            return
        }
        // 让其显示出来
        pullDownTipLabel.isHidden = false
        // 要显示的字符串
        let str = count == 0 ? "没有微博数据" : "\(count) 条微博数据"
        // 设置显示的字符串
        pullDownTipLabel.text = str
        
        // 将其显示出来
        UIView.animate(withDuration: 1, animations: {
            self.pullDownTipLabel.transform = CGAffineTransform.init(translationX: 0, y: self.pullDownTipLabel.frame.height)
            }, completion: { (_) in
                //显示完毕后, 还需要执行动画: 停留1秒, 然后慢慢回去
                UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                    self.pullDownTipLabel.transform = CGAffineTransform.identity
                    }, completion: { (_) in
                        self.pullDownTipLabel.isHidden = true
                })
        })
    
    }


    // MARK: - 懒加载控件

    lazy var pullUpView: UIActivityIndicatorView = {
        let pullUpView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        // 设置颜色
        pullUpView.color = UIColor.black
        return pullUpView
    }()
    
    lazy var xlrefreshControl: XLRefreshControl = XLRefreshControl()
    
    //下拉刷新提示的label
    lazy var pullDownTipLabel: UILabel = {
        let label = UILabel(textColor: UIColor.white, fontSize: 14)
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        //默认隐藏
        label.isHidden = true
        label.frame.size = CGSize(width: HMScreenW, height: 35)
        return label
    }()

}



//将tableView所有的数据源方法写到extention中
    extension XLHomeTableViewController{
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            //return statusArr?.count ?? 0
            return homeViewModel.statusArr?.count ?? 0
        }
        
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellid", for: indexPath) as! XLStatusCell
            let model = self.homeViewModel.statusArr![indexPath.row]
            //cell.status = self.homeViewModel.statusArr![indexPath.row]
            cell.statusViewModel = model
            return cell
        }
        
        override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            
            // 通过将要显示最后一行cell去判断到tableView滚动到底部的逻辑
            if indexPath.row == homeViewModel.statusArr!.count - 1 && pullUpView.isAnimating == false {
                // 将要显示最后一行cell
                print("将要显示最后一行cell")
                // 开启动画
                pullUpView.startAnimating()
                // 去加载更多数据
                loadData()
            }
        }

}
